#pragma once

#include "LogMessage.hpp"
#include <vector>
#include <string>
#include <unistd.h>

class Handler {
public:
  Handler()
  {}

  void operator()(int sock, const std::string& ip, uint16_t& port) {
    while(1) {
      char buffer[1024];
      ssize_t readMes = read(sock, buffer, sizeof(buffer) - 1);
      if(readMes > 0) {
        buffer[readMes] = 0;
      } else if(readMes == 0) {
        LogMessage(NORMAL, _F, _L, "[%s:%d] =___cient disconnected___=", ip.c_str(), port);
        break;
      } else {
        LogMessage(ERROR, _F, _L, "server read fail");
        break;
      }

      LogMessage(NORMAL, _F, _L, "is servering\n\t   [%s:%d] send message ::%s",ip.c_str(), port, buffer);


      ssize_t writeMes = write(sock, buffer, strlen(buffer));
      if(writeMes < 0) {
        LogMessage(ERROR, _F, _L, "server send fail");
      }

    }
    close(sock);
  }

  ~Handler()
  {}
};

class Task {
  public:
    Task()
    {}

    Task(int sockfd, const std::string& ip, const uint16_t& port) 
      :_sockfd(sockfd)
       ,_ip(ip)
       ,_port(port)
    {}

    ~Task()
    {}

    void Run(){
      _handler(_sockfd, _ip, _port);
    }
  private:
    int _sockfd;
    std::string _ip;
    uint16_t _port;
    Handler _handler;
};

